package com.beiding.natgo.server;

import com.beiding.natgo.common.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

@Slf4j
@ServerEndpoint("/server")
public class Sep {


    private SessionManager sessionManager;

    public Sep() {
        this.sessionManager = SessionManagerUtil.getSessionManager();
    }

    @OnOpen
    public void onOpen(Session session) {
        log.info("连接成功");
        sessionManager.put(session);
    }

    @OnClose
    public void onClose(Session session) {
        log.info("关闭连接");
        sessionManager.remove(session);
    }

    @OnMessage
    public void onMessage(Session session, InputStream inputStream) {
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            Message message = (Message) objectInputStream.readObject();
          //  log.info("收到消息 type={}  msg={}", message.getType(), message.getMsg());
            sessionManager.handleMessage(session, message);
        } catch (IOException|ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public SessionManager getSessionManager() {
        return sessionManager;
    }

}
